<?php
/*
 * @Author: 李明
 * @Date: 2021-11-08 16:07:23
 * @LastEditTime: 2022-01-20 13:55:46
 * @LastEditors: 李明
 * @Description:
 * @FilePath: /CRM2.0-PHP/app/Http/Controllers/Utils.php
 * @山东壹零贰肆信息科技有限公司
 */


namespace App\Http\Controllers;

use App\Http\Controllers\common\CommonFun;
use App\Http\Controllers\common\LMReturn;
use App\Http\Controllers\OaManagement\OAController;
use App\Http\Controllers\WeChatService\WeChatServiceUtils;
use App\Models\BankCard;
use App\Models\Image;
use App\Models\Branch;
use App\Models\MassageChangeRecord;
use App\Models\Order;
use App\Models\OrderRecord;
use App\Models\SystemBase;
use App\Models\User;
use App\Models\Worker;
use Illuminate\Support\Env;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;


class Utils
{
    /***
     *  权限判断
     */
    // 普通权限判断
    public static function CommonPer($worker_id)
    {
        return true;
    }

    // 高级权限判断
    public static function SeniorPer($worker_id)
    {
        return true;
    }

    // 顶级权限判断
    public static function TopPer($worker_id)
    {
        return true;
    }

    // OA编辑权限判断
    public static function OAPer($worker_id)
    {
        $power_list = [158, 159, 160, 161, 162];
        $workerRolePower = Worker::where('id', $worker_id)->with('roles.powers')->first();
        if (count($workerRolePower['roles']) > 0) {
            if (count($workerRolePower['roles'][0]['powers']) > 0) {
                foreach ($workerRolePower['roles'][0]['powers'] as $power) {
                    if (in_array($power['id'], $power_list)) {
                        return true;
                    }
                }
            }
            return '抱歉！您没有编辑OA相关权限';
        } else {
            return '您还没有角色，请联系管理员';
        }
    }

    // 新老图片更替问题, type = 1换银行卡id， 2换用户id， 3换订单id
    public static function UpImage($new_img_list, $old_img_list, $bind_id, $type, $recode_worker_id)
    {
        $old_image_id_list = [];
        foreach ($old_img_list as $old_image) {
            $old_image_id_list[] = $old_image->id;
        }
        try {
            DB::beginTransaction(); //开启事务
            $intersection = array_intersect($new_img_list, $old_image_id_list);
            if (isset($old_image_id_list)) {
                foreach ($old_image_id_list as $image_id) {
                    if (!(in_array($image_id, $intersection))) {
                        // 如果老图片的id不在交集则删除
                        $image = Image::find($image_id);
                        // 1 删除 文件图片
                        $exists = Storage::disk('new_ftp')->delete('htdocs/' . $image->img_path);
                        if ($exists) {
                            $image->delete();
                        }
                    }
                }
            }
            if (isset($new_img_list)) {
                foreach ($new_img_list as $new_image_id) {
                    if (!(in_array($new_image_id, $intersection))) {
                        $image = Image::find($new_image_id);
                        $image->record_worker_id = $recode_worker_id;
                        if ($type == 1) {
                            $image->bank_card_id = $bind_id;
                        } elseif ($type == 2) {
                            $image->user_id = $bind_id;
                        } else {
                            $image->order_id = $bind_id;
                        }
                        $image->save();
                    }
                }
            }
            DB::commit(); //提交至数据库
            return 1;
        } catch (\Throwable $th) {
            if (isset($new_img_list)) {
                foreach ($new_img_list as $new_image_id) {
                    if (!(in_array($new_image_id, $intersection))) {
                        $image = Image::find($new_image_id);
                        // 1 删除 文件图片
                        $exists = Storage::disk('new_ftp')->delete('htdocs/' . $image->img_path);
                        if ($exists) {
                            $image->delete();
                        }
                    }
                }
            }
            DB::rollback(); //数据库回滚
            return 0;
        }
    }

    // 查找部门的上级至顶级
    public static function getAllmanage($branch_id, $worker_list)
    {
        $branch = Branch::where('id', $branch_id)->with('manage_workers')->first();
        $p_id = $branch->pid;
        $worker_dic = [];
        $worker_dic['branch_name'] = $branch->name;
        $worker_dic['branch_manages'] = self::getManager($branch['manage_workers']);
        $worker_list[] = $worker_dic;
        if (isset($p_id)) {
            return self::getAllmanage($p_id, $worker_list);
        } else {
            return $worker_list;
        }
    }

    // 查找上级部门
    public static function getUpManage($branch_id)
    {
        $branch = Branch::where('id', $branch_id)->with('manage_workers')->first();
        $worker_dic['branch_name'] = $branch->name;
        $worker_dic['branch_manages'] = self::getManager($branch['manage_workers']);
        return $worker_dic;
    }

    //
    public static function getManager($branch_manage_list)
    {
        $managers_list = [];
        foreach ($branch_manage_list as $manages) {
            $roles = $manages['roles'][0]['id'];
            if ($roles == 33) {
                $magage_dic['name'] = $manages['name'];
                $magage_dic['row'] = 21;
                $managers_list[] = $magage_dic;
            } elseif ($roles == 31) {
                $magage_dic['name'] = $manages['name'];
                $magage_dic['row'] = 23;
                $managers_list[] = $magage_dic;
            } elseif ($roles == 30) {
                $magage_dic['name'] = $manages['name'];
                $magage_dic['row'] = 24;
                $managers_list[] = $magage_dic;
            } elseif ($roles == 32) {
                $magage_dic['name'] = $manages['name'];
                $magage_dic['row'] = 22;
                $managers_list[] = $magage_dic;
            } elseif ($roles == 29) {
                $magage_dic['name'] = $manages['name'];
                $magage_dic['row'] = 25;
                $managers_list[] = $magage_dic;
            } elseif ($roles == 1) {
                $magage_dic['name'] = $manages['name'];
                $magage_dic['row'] = 26;
                $managers_list[] = $magage_dic;
            }
        }
        return $managers_list;
    }

    // 查找子部门及管理员
    public static function getChildBranch($branch_id, $worker_manager_list, $child_branch_id)
    {
        $worker_manager = Branch::where('id', $child_branch_id)->with('manage_workers.roles')->first();
        if (isset($worker_manager)) {
            foreach ($worker_manager['manage_workers'] as $worker_managers) {
                if ($worker_managers['user_status'] == 1) {
                    $worker_manager_dic['id'] = $worker_managers['id'];
                    $worker_manager_dic['role'] = $worker_managers['role'][0]['id'];
                    $worker_manager_list[] = $worker_manager_dic;
                }
            }
            if ($worker_manager['pid'] == 3) {
                return 0;
            }
            if ($branch_id == $child_branch_id) {
                return $worker_manager_list;
            }
            return self::getChildBranch($worker_manager->id, $worker_manager_list, $worker_manager['pid']);
        } else {
            return $worker_manager_list;
        }
    }

    /**
     * @description:
     * @param string $type 1是员工，2是用户
     * @param {*} $object 1的话就是 worker 对象，  2的话就是user 对象
     * @return {*}password加密的密码， message提示文字
     */
    public static function passwordSystem($type, $object)
    {
        $system = SystemBase::find(1);
        $password_type = $system->password_type;

        if ($password_type == '1') { // 1固定密码 2手机号后六位  3身份证后六位
            $password = $system->default_password ?? '';
            $message = $password != '' ? '修改成功,重置为系统默认密码' : '没有设置系统默认密码';
        } elseif ($password_type == '2') {
            $password = ($type == '1' ? substr($object->contactNum, -6) : substr($object->contact_manner, -6)) ?? '';
            $message = $password != '' ? '修改成功，重置为客户手机号后六位' : '客户没有绑定手机号';
        } elseif ($password_type == '3') {
            $password = substr($object->id_number, -6) ?? '';
            $message = $password != '' ? '修改成功，重置为客户身份证后六位' : '客户没有绑定身份证';
        } else {
            $password = $system->default_password ?? '';
            $message = $password != '' ? '修改成功,重置为系统默认密码' : '没有设置系统默认密码';
        }
        $password_md5 = CommonFun::md5($password);
        $r_data['password'] = $password_md5;
        $r_data['message'] = $message;
        return $r_data;
    }

    /**
     * @description: 处理金额
     * @param string $money
     * @return string
     */
    public static function moneyDeal($money)
    {
        if ($money >= 10000) {
            $money = $money / 10000;
            return $money . '万元';
        } else {
            return $money . '元';
        }
    }

    // 递归排序部门查找上下级1
    public static function getPidBranch($branch_id, $branch_list)
    {
        $where = [];
        $where[] = ['pid', $branch_id];
        $where[] = ['is_effective', 1];
        $where[] = ['hid', null];
        $branchs = Branch::where($where)->first();
        if ($branchs) {
            $branch_dics['id'] = $branchs->id;
            $branch_dics['branch_code'] = $branchs->branch_code;
            $branch_dics['name'] = $branchs->name;
            $branch_dics['pid'] = $branch_id;
            $branch_dics['hid'] = null;
            $branch_dics['commission_rate'] = $branchs->commission_rate;
            $branch_dics['task'] = $branchs->task;
            $branch_dics['is_important'] = $branchs->is_important;
            $branch_dics['remark'] = $branchs->remark;
            $branch_dics['weight'] = $branchs->weight;
            $branch_dics['create_time'] = $branchs->create_time;
            $branch_dics['update_time'] = $branchs->update_time;
            $branch = self::getPidBranch($branchs->id, []);
            if ($branch) {
                $branch_dics['treeList'] = $branch;
            }
            $branch_list[] = $branch_dics;
            return self::getHidBranch($branchs->id, $branch_list);
        } else {
            return $branch_list;
        }
    }

    // 递归排序部门查找顺序
    public static function getHidBranch($branch_id, $branch_list)
    {
        $where = [];
        $where[] = ['is_effective', 1];
        $where[] = ['hid', $branch_id];
        $branch = Branch::where($where)->first();
        if ($branch) {
            $branch_dics['id'] = $branch->id;
            $branch_dics['branch_code'] = $branch->branch_code;
            $branch_dics['name'] = $branch->name;
            $branch_dics['pid'] = $branch->pid;
            $branch_dics['hid'] = $branch_id;
            $branch_dics['commission_rate'] = $branch->commission_rate;
            $branch_dics['task'] = $branch->task;
            $branch_dics['is_important'] = $branch->is_important;
            $branch_dics['remark'] = $branch->remark;
            $branch_dics['weight'] = $branch->weight;
            $branch_dics['create_time'] = $branch->create_time;
            $branch_dics['update_time'] = $branch->update_time;
            $branchs = self::getPidBranch($branch->id, []);
            if ($branchs) {
                $branch_dics['treeList'] = $branchs;
            }
            $branch_list[] = $branch_dics;
            return self::getHidBranch($branch->id, $branch_list);
        }
        return $branch_list;
    }

    // 将小数组按照hid排序
    public static function getArrayHid($new_list, $pid_list, $id)
    {
        foreach ($pid_list as $pid_dic) {
            if ($pid_dic['hid'] == $id) {
                $new_list[] = $pid_dic;
                $pid_id = $pid_dic['id'];
                return self::getArrayHid($new_list, $pid_list, $pid_id);
            }
        }
        return $new_list;
    }

    // 利用数组操作将查到的所有部门整理
    public static function getArrayBranch($branchs_dics, $branch_id)
    {
        $branchs_list = [];
        if (isset($branchs_dics[$branch_id])) {
            foreach ($branchs_dics[$branch_id] as $branch_dic) {
                $treeList = self::getArrayBranch($branchs_dics, $branch_dic['id']);
                if ($treeList) {
                    $branch_dic['treeList'] = $treeList;
                }
                $branchs_list[] = $branch_dic;
            }
        }
        return $branchs_list;
    }

    // 得到分公司的部门id
    public static function getBranchId($branch_id)
    {
        $branch = Branch::find($branch_id);
        if ($branch->pid == 3 || $branch->id == 3) {
            return $branch_id;
        } else {
            return self::getBranchId($branch->pid);
        }
    }

    // 得到上级部门管理员
    public static function getBranchManager($branch_id, $worker_manager_list)
    {
        $in_branch = Branch::where('id', $branch_id)->with('manage_workers.roles')->first();
        if ($in_branch['pid'] != 0) {
            if ($in_branch['manage_workers']) {
                foreach ($in_branch['manage_workers'] as $manager) {
                    if (count($manager['roles']) != 0) {
                        $manager_dic['name'] = $manager['name'];
                        $manager_dic['role'] = $manager['roles'][0]['id'];
                        $worker_manager_list[] = $manager_dic;
                    }
                }
            }
            return self::getBranchManager($in_branch['pid'], $worker_manager_list);
        } else {
            return $worker_manager_list;
        }
    }


    // 得到上级部门(国邦盛世)
    public static function getPBranch($branch_id, $worker_manager_list)
    {
        $in_branch = Branch::where('id', $branch_id)->first();
        if ($in_branch['pid'] != 0) {
            $worker_manager_list[] = $in_branch['name'];
            return self::getPBranch($in_branch['pid'], $worker_manager_list);
        } else {
            return $worker_manager_list;
        }
    }

    // 得到所有子部门列表
    public static function getChildBranchs($branch_id, $branch_list)
    {
        $branchs = Branch::where('pid', $branch_id)->where('is_effective', 1)->get();
        if (count($branchs) > 0) {
            foreach ($branchs as $branch) {
                if (!(in_array($branch->id, $branch_list))) {
                    $branch_list[] = $branch->id;
                    $branch_list = self::getChildBranchs($branch->id, $branch_list);
                }
            }
            return $branch_list;
        } else {
            return $branch_list;
        }
    }

    // 取整规则归纳，1.向上取整，2.向下取整，3.四舍五入保留$keeps位小数(0位小数就是取整数)，4.无进位直接取整，5.无进位保留$keeps位小数
    public static function getNumRules($num, $type, $keeps = 0)
    {
        $type = env('INTEGER_RULES', 3);
        $keeps = env('KEEPS', 0);
        // INTEGER_RULES = 3  # 取整方式1.向上取整，2.向下取整，3.四舍五入保留$keeps位小数(0位小数就是取整数)，4.无进位直接取整，5.无进位保留$keeps位小数
        // KEEPS=2 #保留几位小数
        if ($type == 1) {
            return ceil($num);
        } elseif ($type == 2) {
            return floor($num);
        } elseif ($type == 3) {
            return round($num, $keeps);
        } elseif ($type == 4) {
            return intval($num);
        } elseif ($type == 5) {
            return intval($num * pow(10, $keeps)) / pow(10, $keeps);
        } else {
            return 0;
        }
    }

    /**
     * @description:
     * @description: 查询子孙部门们
     * @param {*} $branch_id  要查询的部门  必须是他有权限管理的部门
     * @param {*} $is_have_self  是否包含要查询的部门自己,默认包含
     * @return array branch_id_list 返回的  子孙部门的id list
     */
    public static function getChildSonBranchs($branch_id, $is_have_self = true)
    {
        $child_branchs = $is_have_self ? [$branch_id] : [];
        return  OAController::getChildBranchs($branch_id, OAController::getAllBranchs(), $child_branchs);
    }

    /**
     * @description:
     * @description: 查询子孙部门们
     * @param {*} $worker  要查询员工
     * @param {*} $is_have_self  是否包含要查询的员工的顶级管理部门,默认包含
     * @return array branch_id_list 返回的  子孙部门的id list
     */
    public static function getWorkerChildSonBranchs($worker, $is_have_self = true)
    {
        $branch_id = $worker->branchesManage->first()->id ?? '';
        if ($branch_id == '') {
            return [];
        }
        return  Utils::getChildSonBranchs($branch_id, $is_have_self);
    }
    /**
     * @description: 处理Resources 之后的 分页问题
     * @param {*} $res_list  Resources 之后的list
     * @param {*} $model_list 查询到的原始list
     * @return {*}
     */
    public static function deal_page_resources($res_list, $model_list)
    {
        $model_list = json_decode(json_encode($model_list), true);
        $return_datas['current_page'] = $model_list['current_page'];
        $return_datas['from'] = $model_list['from'];
        $return_datas['last_page'] = $model_list['last_page'];
        $return_datas['per_page'] = $model_list['per_page'];
        $return_datas['to'] = $model_list['to'];
        $return_datas['total'] = $model_list['total'];
        $return_datas['data'] = $res_list;
        return $return_datas;
    }
    // 根据修改记录修改客户或银行卡信息
    public static function updateUserABankCard($massage_change_id)
    {
        $massage_changes = MassageChangeRecord::where('id', $massage_change_id)->with('bank_card')->with('old_bank_card')->with('oa_records')->with('order.user')->first();
        if ($massage_changes->record_type == 2) {
            Order::where('id', $massage_changes->order_id)->update(['bank_card_id' => $massage_changes->bank_card_id]);
            try {
                $new_bank_card = $massage_changes['bank_card'];
                $old_bank_card = $massage_changes['old_bank_card'];
                $update_msg = '原开户行：' . $old_bank_card['bank_sum_name'] . '原卡号：' . $old_bank_card['bank_num'] . "\n" . '新开户行' . $new_bank_card['bank_sum_name'] . '新卡号：' . $new_bank_card['bank_num'];
                $worker_id = $massage_changes['oa_records'][0]['worker_id'];
                $new_order_record = new OrderRecord();
                $new_order_record->order_id = $massage_changes->order_id;
                $new_order_record->type = 3;
                $new_order_record->worker_id = $worker_id;
                $new_order_record->audit_step = 3;
                $new_order_record->is_success = 1;
                $new_order_record->remark = $update_msg;
                $new_order_record->save();
            } catch (\Throwable $th) {
            }
//            try {
//                $open_id = $massage_changes->order->user->public_open_id;
//                $contract_no = $massage_changes->order->contract_no;
//                // 通过审核在公众号后给客户发消息
//                $sta = WeChatServiceUtils::SendOrderChange($contract_no, $open_id);
//            } catch (\Throwable $th) {
//            }
        } elseif ($massage_changes->record_type == 1) {
            $user = User::find($massage_changes->user_id);
            if ($massage_changes->user_name) {
                $user->name = $massage_changes->user_name;
            }
            if ($massage_changes->count_num) {
                $user->account = $massage_changes->count_num;
            }
            if ($massage_changes->img_card_id) {
                $user->id_number = $massage_changes->img_card_id;
                $birth = substr($massage_changes->img_card_id, 6, 8);
                $year = substr($birth, 0, 4);
                $mouth = substr($birth, 4, 2);
                $day = substr($birth, 6, 2);
                $birthday = $year . '-' . $mouth . '-' . $day;      //通过身份证号解析出的生日
                $sex_num = substr($massage_changes->img_card_id, 16, 1);
                if ((int)($sex_num) % 2 == 0) {
                    $sex = 2;
                } else {
                    $sex = 1;
                }
                $user->birthday = $birthday;
                $user->sex = $sex;
            }
            if ($massage_changes->phone_num) {
                $user->contact_manner = $massage_changes->phone_num;
            }
            if ($massage_changes->new_email) {
                $user->email = $massage_changes->new_email;
            }
            if ($massage_changes->new_address) {
                $user->address = $massage_changes->new_address;
            }
            if ($massage_changes->id_type) {
                $user->id_type = $massage_changes->id_type;
            }
            try {
                if ($massage_changes->address_code) {
                    $area_code = $massage_changes->address_code;
                    $user->area_code = $area_code;
                    $city_code = floor($area_code / 100) * 100;
                    $pro_code = floor($area_code / 10000) * 10000;
                    $user->city_code = $city_code;
                    $user->pro_code = $pro_code;
                }
            } catch (\Throwable $th) {
            }
            $user->save();
            if ($massage_changes->img_id_list && $massage_changes->img_id_list != '') {
                $old_img_list = [];
                $new_img_list = explode('-', $massage_changes->img_id_list);
                if ($massage_changes->old_img_id_list != null) {
                    $old_img_list = explode('-', $massage_changes->old_img_id_list);
                }
                foreach ($new_img_list as $new_image_id) {
                    $image = Image::find($new_image_id);
                    if (isset($image)) {
                        $image->user_id = $massage_changes->user_id;
                        $image->save();
                    }
                }
                if (count($old_img_list) > 0) {
                    foreach ($old_img_list as $old_img_id) {
                        if (in_array($old_img_id, $new_img_list) == false) {
                            $old_image = Image::find($old_img_id);
                            if (isset($old_image)) {
                                try {
                                    // 1 删除 文件图片
                                    $exists = Storage::disk('ftp')->delete('htdocs/' . $old_image['img_path']);
                                } catch (\Throwable $th) {
                                }
                                $old_image->delete();
                                // 2 删除 数据库图片
//                                if ($exists) {
//                                    $old_image->delete();
//                                }
                            }
                        }
                    }
                }
            }
        } elseif ($massage_changes->record_type == 3) {
            $bank_card = BankCard::find($massage_changes->bank_card_id);
            if ($massage_changes->id_type) {
                $bank_card->bank_id = $massage_changes->id_type;
            }
            if ($massage_changes->user_name) {
                $bank_card->account_name = $massage_changes->user_name;
            }
            if ($massage_changes->count_num) {
                $bank_card->bank_num = $massage_changes->count_num;
            }
            if ($massage_changes->new_address) {
                $bank_card->bank_sum_name = $massage_changes->new_address;
            }
            if ($massage_changes->img_id_list && $massage_changes->img_id_list != '') {
                $old_img_list = [];
                $new_img_list = explode('-', $massage_changes->img_id_list);
                if ($massage_changes->old_img_id_list != null) {
                    $old_img_list = explode('-', $massage_changes->old_img_id_list);
                }
                foreach ($new_img_list as $new_image_id) {
                    $image = Image::find($new_image_id);
                    if (isset($image)) {
                        $image->bank_card_id = $massage_changes->bank_card_id;
                        $image->save();
                    }
                }
                if (count($old_img_list) > 0) {
                    foreach ($old_img_list as $old_img_id) {
                        if (in_array($old_img_id, $new_img_list) == false) {
                            $old_image = Image::find($old_img_id);
                            if (isset($old_image)) {
                                try {
                                    // 1 删除 文件图片
                                    $exists = Storage::disk('ftp')->delete('htdocs/' . $old_image['img_path']);
                                } catch (\Throwable $th) {
                                }
                                $old_image->delete();
                            }
                        }
                    }
                }
            }
            $bank_card->status = 1;
            $bank_card->save();
        }
    }
}
